{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "%matplotlib inline\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import pickle\n",
    "from pathlib import Path\n",
    "import sys\n",
    "sys.path.append('/home/billy/projects/mmdetection')\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import mmcv\n",
    "from mmcv.runner import load_checkpoint, parallel_test, obj_from_dict\n",
    "from mmcv.parallel import scatter, collate, MMDataParallel\n",
    "from mmdet.core.evaluation.kitti_eval import get_official_eval_result\n",
    "from mmdet import datasets\n",
    "from mmdet.core import results2json, coco_eval\n",
    "from mmdet.datasets import build_dataloader\n",
    "from mmdet.models import build_detector, detectors\n",
    "from mmdet.datasets import utils\n",
    "import tools.kitti_common as kitti\n",
    "import numpy as np\n",
    "import torch.utils.data\n",
    "from mmdet.datasets.utils import merge_second_batch\n",
    "from mmdet.core.evaluation.class_names import get_classes\n",
    "torch.cuda.set_device(0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Read Config file"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "config_path = \"/home/billy/projects/mmdetection/configs/bevnet.py\"\n",
    "cfg = mmcv.Config.fromfile(config_path)\n",
    "cfg.model.pretrained = None\n",
    "cfg.data.test.test_mode = True\n",
    "dataset = utils.get_dataset(cfg.data.val)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Build Network, Dataloader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "checkpoint = \"/home/billy/projects/mmdetection/logs/bevnet/.backup/epoch_45.pth\"\n",
    "model = build_detector(\n",
    "            cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)\n",
    "load_checkpoint(model, checkpoint)\n",
    "model = MMDataParallel(model, device_ids=[0])\n",
    "\n",
    "data_loader = build_dataloader(\n",
    "    dataset,\n",
    "    #cfg.data.imgs_per_gpu,\n",
    "    1,\n",
    "    #cfg.data.workers_per_gpu,\n",
    "    0,\n",
    "    num_gpus=1,\n",
    "    collate_fn=cfg.data.collate_fn,\n",
    "    shuffle=False,\n",
    "    dist=False)\n",
    "data_loader = iter(data_loader)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Example #000040\n"
     ]
    },
    {
     "ename": "NameError",
     "evalue": "name 'compute_boxes3d' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-26-4712ffcb2b2a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m     14\u001b[0m \u001b[0mcalib\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mCalibration\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mos\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpath\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mjoin\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"/home/billy/datasets/KITTI/training/calib\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'%06d.txt'\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;34m'sample_idx'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     15\u001b[0m \u001b[0mgt_3dboxes\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mobject\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mbox3d\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mobject\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mobjects\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mobject\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mtype\u001b[0m \u001b[0;32min\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0;34m'Car'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'Van'\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 16\u001b[0;31m \u001b[0mboxes3d_rgb\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0m_\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mcompute_boxes3d\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mobjects\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcalib\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     17\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     18\u001b[0m \u001b[0mgt_3dboxes\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0marray\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mgt_3dboxes\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mdtype\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mfloat32\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
      "\u001b[0;31mNameError\u001b[0m: name 'compute_boxes3d' is not defined"
     ]
    }
   ],
   "source": [
    "import simplevis\n",
    "from mmdet.datasets.kitti_utils import read_lidar, Calibration, read_label,project_rect_to_velo, \\\n",
    "draw_projected_boxes3d,centers2corners,compute_boxes3d\n",
    "import mmcv\n",
    "import os\n",
    "plt.rcParams['figure.figsize'] = [10, 10]\n",
    "data = next(data_loader)\n",
    "print(\"Example #%06d\" % data['sample_idx'][0])\n",
    "lidar_path = os.path.join(\"/home/billy/datasets/KITTI/training/velodyne/%06d.bin\" % data['sample_idx'][0])\n",
    "objects = read_label(os.path.join(\"/home/billy/datasets/KITTI/training/label_2\", '%06d.txt' % data['sample_idx'][0]))\n",
    "rgb = mmcv.imread(os.path.join(\"/home/billy/datasets/KITTI/training/image_2\", '%06d.png' % data['sample_idx'][0]))\n",
    "\n",
    "points = read_lidar(lidar_path)\n",
    "calib = Calibration(os.path.join(\"/home/billy/datasets/KITTI/training/calib\", '%06d.txt' % data['sample_idx'][0]))\n",
    "gt_3dboxes = [object.box3d for object in objects if object.type in ['Car', 'Van']]\n",
    "boxes3d_rgb, _ = compute_boxes3d(objects, calib)\n",
    "\n",
    "gt_3dboxes = np.array(gt_3dboxes, dtype=np.float32)\n",
    "#boxes3d_rgb,_ = centers2corners(gt_3dboxes, calib)\n",
    "draw_projected_boxes3d(rgb, boxes3d_rgb, (255,0,0))\n",
    "try:\n",
    "    gt_3dboxes[:, :3] = project_rect_to_velo(gt_3dboxes[:, :3], calib)\n",
    "except:\n",
    "    gt_3dboxes = np.empty((0,7),dtype=np.float32)\n",
    "    \n",
    "with torch.no_grad():\n",
    "    results = model(return_loss=False, **data)[0]\n",
    "boxes_lidar = results[\"box3d_lidar\"]\n",
    "scores = results[\"scores\"]\n",
    "vis_voxel_size = [0.1, 0.1, 0.1]\n",
    "vis_point_range = [0., -32., -2.3, 52.8, 32., 1.2]\n",
    "bev_map = simplevis.point_to_vis_bev(points, vis_voxel_size, vis_point_range)\n",
    "bev_map = simplevis.draw_box_in_bev(bev_map, vis_point_range, boxes_lidar, [0, 255, 0], 2, labels=map(lambda x:\"%.02f\" % x, scores))\n",
    "bev_map = simplevis.draw_box_in_bev(bev_map, vis_point_range, gt_3dboxes, [255, 0, 0], 2)\n",
    "plt.imshow(bev_map) \n",
    "plt.figure()\n",
    "plt.imshow(rgb[:,:,::-1])"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.1"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
